# Event-Driven Continual Learning Framework
#
# This package provides a comprehensive event-driven architecture for
# continual learning strategies, enabling loose coupling between training
# logic and strategy implementations.
#
# Quick Start:
#   1. Create a strategy: class MyStrategy(StrategyEventHandler): ...
#   2. Register strategy: global_dispatcher.register_handler(strategy)
#   3. Use in training: CL module will automatically dispatch events
#
# Documentation:
#   - README.md: Detailed documentation with zero-to-hero explanation
#   - QUICKSTART.md: 5-minute quick start guide
#   - ARCHITECTURE.md: System architecture overview

# Core interfaces - import directly from specific modules to avoid circular imports
from continuallearning.events.interfaces.strategy_interfaces import (
    StrategyEventHandlerInterface as StrategyEventHandler,
    LossComputationInterface,
    BatchProcessorInterface,
    MemoryManagerInterface,
)
from continuallearning.events.interfaces.base_interfaces import (
    EventDispatcherInterface as IEventDispatcher,
)
from continuallearning.events.interfaces.utility_interfaces import (
    ComponentRegistryInterface as IComponentRegistry,
)

# Import EventType and BaseEventData from unified core
from continuallearning.events.core.unified_event_types import (
    EventType,
    BaseEventData,
)

# Core implementations from unified modules
from continuallearning.events.core.unified_event_types import (
    StrategyEvent,
    EventFactory,
    TaskEvent,
    TrainingEvent,
    EvaluationEvent,
    DataEvent,
    ModelEvent,
    LoggingEvent,
    ErrorEvent,
)

from continuallearning.events.core.unified_handlers import (
    BaseEventHandler,
    FunctionalEventHandler,
    ChainableEventHandler,
    ConditionalEventHandler,
    AsyncEventHandler,
    BatchEventHandler,
    RetryEventHandler,
)

from continuallearning.events.core.unified_dispatcher import (
    EventDispatcher as AdvancedEventDispatcher,
)

from continuallearning.registry.component_registry import (
    AdvancedComponentRegistry as ComponentRegistry,
    strategy_registry,
)

# Strategy examples
from continuallearning.events.strategies.examples import (
    AdvancedEWCStrategy,
    AdvancedExperienceReplayStrategy,
)

# More strategy examples
from continuallearning.events.strategies.event_driven_examples import (
    MetaLearningStrategy,
    AdaptiveLearningRateStrategy,
    MemoryConsolidationStrategy,
    DynamicArchitectureStrategy,
)


# Create a simple strategy decorator
def strategy(name=None, version="1.0.0", description="", tags=None, categories=None):
    """
    Simple strategy decorator for registering continual learning strategies.

    Args:
        name: Strategy name (defaults to class name)
        version: Strategy version
        description: Strategy description
        tags: List of tags
        categories: List of categories

    Returns:
        Decorated class
    """

    def decorator(cls):
        strategy_name = name or cls.__name__
        # For now, just return the class as-is
        # A full implementation would register with strategy_registry
        cls._strategy_metadata = {
            "name": strategy_name,
            "version": version,
            "description": description,
            "tags": tags or [],
            "categories": categories or [],
        }
        return cls

    return decorator


# Global instances - the heart of the event system
global_dispatcher = AdvancedEventDispatcher()
global_registry = ComponentRegistry(name="GlobalRegistry")


# Convenience functions for quick start
def create_strategy(strategy_class, **kwargs):
    """
    Convenience function to create and register a strategy.

    Args:
        strategy_class: The strategy class to instantiate
        **kwargs: Arguments to pass to the strategy constructor

    Returns:
        The created strategy instance

    Example:
        >>> ewc = create_strategy(AdvancedEWCStrategy, regularization_weight=1000)
    """
    strategy_instance = strategy_class(**kwargs)
    global_dispatcher.register_handler(strategy_instance)
    return strategy_instance


def list_available_strategies():
    """
    List all available strategy classes.

    Returns:
        Dict mapping strategy names to classes
    """
    return {
        "EWC": AdvancedEWCStrategy,
        "ExperienceReplay": AdvancedExperienceReplayStrategy,
        "MetaLearning": MetaLearningStrategy,
        "AdaptiveLR": AdaptiveLearningRateStrategy,
        "MemoryConsolidation": MemoryConsolidationStrategy,
        "DynamicArchitecture": DynamicArchitectureStrategy,
    }


def get_registered_strategies():
    """
    Get all currently registered strategies.

    Returns:
        List of registered strategy names
    """
    return list(global_dispatcher.handlers.keys())


def setup_basic_strategies():
    """
    Setup basic EWC and Replay strategies with default parameters.
    Useful for quick experimentation.

    Returns:
        Dict of created strategies
    """
    strategies = {
        "ewc": create_strategy(AdvancedEWCStrategy, regularization_weight=1000),
        "replay": create_strategy(AdvancedExperienceReplayStrategy, memory_size=1000),
    }
    print(f"Created basic strategies: {list(strategies.keys())}")
    return strategies


def clear_all_strategies():
    """
    Clear all registered strategies from the global dispatcher.
    Useful for testing or resetting the system.
    """
    global_dispatcher.handlers.clear()
    print("All strategies cleared from global dispatcher")


# Debugging and monitoring utilities
def enable_debug_mode():
    """Enable debug mode for the global dispatcher."""
    global_dispatcher.enable_debug_mode()
    print("Debug mode enabled - event flow will be logged")


def get_system_status():
    """
    Get a summary of the current event system status.

    Returns:
        Dict with system status information
    """
    return {
        "registered_strategies": len(global_dispatcher.handlers),
        "strategy_names": list(global_dispatcher.handlers.keys()),
        "debug_mode": getattr(global_dispatcher, "debug_mode", False),
        "total_events_processed": len(getattr(global_dispatcher, "event_history", [])),
        "available_strategy_classes": len(list_available_strategies()),
    }


# Version info
__version__ = "1.0.0"
__author__ = "Lightning Continual Learning Framework"

# All public exports
__all__ = [
    # Core interfaces
    "StrategyEventHandler",
    "IEventDispatcher",
    "IComponentRegistry",
    "EventType",
    # Core implementations
    "StrategyEvent",
    "EventFactory",
    "TaskEvent",
    "TrainingEvent",
    "EvaluationEvent",
    "DataEvent",
    "ModelEvent",
    "LoggingEvent",
    "ErrorEvent",
    "BaseEventHandler",
    "FunctionalEventHandler",
    "ChainableEventHandler",
    "ConditionalEventHandler",
    "AsyncEventHandler",
    "BatchEventHandler",
    "RetryEventHandler",
    "AdvancedEventDispatcher",
    "ComponentRegistry",
    "strategy_registry",
    "strategy",
    # Global instances
    "global_dispatcher",
    "global_registry",
    # Strategy examples
    "AdvancedEWCStrategy",
    "AdvancedExperienceReplayStrategy",
    "MetaLearningStrategy",
    "AdaptiveLearningRateStrategy",
    "MemoryConsolidationStrategy",
    "DynamicArchitectureStrategy",
    # Convenience functions
    "create_strategy",
    "list_available_strategies",
    "get_registered_strategies",
    "setup_basic_strategies",
    "clear_all_strategies",
    "enable_debug_mode",
    "get_system_status",
    # Meta info
    "__version__",
    "__author__",
]

# Print helpful info when package is imported
print(f"🚀 Event-Driven CL Framework v{__version__} loaded!")
print(
    f"📚 Quick start: from continuallearning.events import create_strategy, AdvancedEWCStrategy"
)
print(f"📖 Documentation available in: README.md, QUICKSTART.md, ARCHITECTURE.md")
print(f"🔧 Available strategies: {', '.join(list_available_strategies().keys())}")
